package org.jeecg.modules.order.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.aspect.annotation.PermissionData;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.customer.entity.BusCustomer;
import org.jeecg.modules.customer.service.IBusCustomerService;
import org.jeecg.modules.order.entity.BusOrder;
import org.jeecg.modules.order.entity.BusOrderItem;
import org.jeecg.modules.order.entity.BusOrderPics;
import org.jeecg.modules.order.service.IBusOrderItemService;
import org.jeecg.modules.order.service.IBusOrderPicsService;
import org.jeecg.modules.order.service.IBusOrderService;
import org.jeecg.modules.order.vo.BusOrderPage;
import org.jeecg.modules.system.service.ISysUserService;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Description: 订单表
 * @Author: jeecg-boot
 * @Date: 2021-07-13
 * @Version: V1.0
 */
@Api(tags = "订单表")
@RestController
@RequestMapping("/order/busOrder")
@Slf4j
public class BusOrderController {
    @Autowired
    private IBusOrderService busOrderService;
    @Autowired
    private IBusOrderItemService busOrderItemService;
    @Autowired
    private IBusOrderPicsService busOrderPicsService;
    @Autowired
    private IBusCustomerService customerService;

    /**
     * 分页列表查询
     *
     * @param busOrder
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "订单表-分页列表查询")
    @ApiOperation(value = "订单表-分页列表查询", notes = "订单表-分页列表查询")
    @GetMapping(value = "/list")
    @PermissionData(pageComponent = "order/BusOrderList")
    public Result<?> queryPageList(BusOrder busOrder,
                                   @RequestParam(value = "customerId", required = false) String customerId,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   HttpServletRequest req) {
        QueryWrapper<BusOrder> queryWrapper = QueryGenerator.initQueryWrapper(busOrder, req.getParameterMap());
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

        Page<BusOrder> page = new Page<BusOrder>(pageNo, pageSize);
        String userId = loginUser.getId();

        LambdaQueryWrapper<BusCustomer> customerLambdaQueryWrapper = new LambdaQueryWrapper<>();
        customerLambdaQueryWrapper.eq(BusCustomer::getSysUserId, userId);
        BusCustomer busCustomer = customerService.getOne(customerLambdaQueryWrapper);
        if (customerId != null && !busCustomer.getId().equals(customerId) && busCustomer.getManagerType() == 0) {
            Result.error("客户信息不正确");
        }
        if (busCustomer != null &&( busCustomer.getManagerType() == null || busCustomer.getManagerType() == 0)) {
            queryWrapper.eq("cus_id", customerId);
        }
        queryWrapper.orderByDesc("create_time");
        IPage<BusOrder> pageList = busOrderService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

    @AutoLog(value = "订单表-分页列表查询")
    @ApiOperation(value = "订单表-分页列表查询", notes = "订单表-分页列表查询")
    @GetMapping(value = "/orderList")
    public Result<?> userList(BusOrder busOrder,
                              @RequestParam("customerId") String customerId,
                              @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                              @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                              HttpServletRequest req) {
        QueryWrapper<BusOrder> queryWrapper = QueryGenerator.initQueryWrapper(busOrder, req.getParameterMap());
        queryWrapper.eq("cus_id", customerId);
        queryWrapper.orderByDesc("create_time");
        Page<BusOrder> page = new Page<BusOrder>(pageNo, pageSize);
        IPage<BusOrder> pageList = busOrderService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

    /**
     * 添加
     *
     * @param busOrderPage
     * @return
     */
    @AutoLog(value = "订单表-添加")
    @ApiOperation(value = "订单表-添加", notes = "订单表-添加")
    @PostMapping(value = "/add")
    public Result<?> add(@RequestBody BusOrderPage busOrderPage) {
        BusOrder busOrder = new BusOrder();
        BeanUtils.copyProperties(busOrderPage, busOrder);
        busOrderService.saveMain(busOrder, busOrderPage.getBusOrderItemList(), busOrderPage.getBusOrderPicsList());
        return Result.OK("添加成功！");
    }

    /**
     * 编辑
     *
     * @param busOrderPage
     * @return
     */
    @AutoLog(value = "订单表-编辑")
    @ApiOperation(value = "订单表-编辑", notes = "订单表-编辑")
    @PutMapping(value = "/edit")
    public Result<?> edit(@RequestBody BusOrderPage busOrderPage) {
        BusOrder busOrder = new BusOrder();
        BeanUtils.copyProperties(busOrderPage, busOrder);
        BusOrder busOrderEntity = busOrderService.getById(busOrder.getId());
        if (busOrderEntity == null) {
            return Result.error("未找到对应数据");
        }
        busOrderService.updateMain(busOrder, busOrderPage.getBusOrderItemList(), busOrderPage.getBusOrderPicsList());
        return Result.OK("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "订单表-通过id删除")
    @ApiOperation(value = "订单表-通过id删除", notes = "订单表-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
        busOrderService.delMain(id);
        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "订单表-批量删除")
    @ApiOperation(value = "订单表-批量删除", notes = "订单表-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.busOrderService.delBatchMain(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功！");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "订单表-通过id查询")
    @ApiOperation(value = "订单表-通过id查询", notes = "订单表-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<?> queryById(@RequestParam(name = "id", required = true) String id) {
        BusOrder busOrder = busOrderService.getById(id);
        if (busOrder == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(busOrder);

    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "订单明细通过主表ID查询")
    @ApiOperation(value = "订单明细主表ID查询", notes = "订单明细-通主表ID查询")
    @GetMapping(value = "/queryBusOrderItemByMainId")
    public Result<?> queryBusOrderItemListByMainId(@RequestParam(name = "id", required = true) String id) {
        List<BusOrderItem> busOrderItemList = busOrderItemService.selectByMainId(id);
        return Result.OK(busOrderItemList);
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "订单图片通过主表ID查询")
    @ApiOperation(value = "订单图片主表ID查询", notes = "订单图片-通主表ID查询")
    @GetMapping(value = "/queryBusOrderPicsByMainId")
    public Result<?> queryBusOrderPicsListByMainId(@RequestParam(name = "id", required = true) String id) {
        List<BusOrderPics> busOrderPicsList = busOrderPicsService.selectByMainId(id);
        return Result.OK(busOrderPicsList);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param busOrder
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, BusOrder busOrder) {
        // Step.1 组装查询条件查询数据
        QueryWrapper<BusOrder> queryWrapper = QueryGenerator.initQueryWrapper(busOrder, request.getParameterMap());
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

        //Step.2 获取导出数据
        List<BusOrder> queryList = busOrderService.list(queryWrapper);
        // 过滤选中数据
        String selections = request.getParameter("selections");
        List<BusOrder> busOrderList = new ArrayList<BusOrder>();
        if (oConvertUtils.isEmpty(selections)) {
            busOrderList = queryList;
        } else {
            List<String> selectionList = Arrays.asList(selections.split(","));
            busOrderList = queryList.stream().filter(item -> selectionList.contains(item.getId())).collect(Collectors.toList());
        }

        // Step.3 组装pageList
        List<BusOrderPage> pageList = new ArrayList<BusOrderPage>();
        for (BusOrder main : busOrderList) {
            BusOrderPage vo = new BusOrderPage();
            BeanUtils.copyProperties(main, vo);
            List<BusOrderItem> busOrderItemList = busOrderItemService.selectByMainId(main.getId());
            vo.setBusOrderItemList(busOrderItemList);
            List<BusOrderPics> busOrderPicsList = busOrderPicsService.selectByMainId(main.getId());
            vo.setBusOrderPicsList(busOrderPicsList);
            pageList.add(vo);
        }

        // Step.4 AutoPoi 导出Excel
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        mv.addObject(NormalExcelConstants.FILE_NAME, "订单表列表");
        mv.addObject(NormalExcelConstants.CLASS, BusOrderPage.class);
        mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("订单表数据", "导出人:" + sysUser.getRealname(), "订单表"));
        mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
        return mv;
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            MultipartFile file = entity.getValue();// 获取上传文件对象
            ImportParams params = new ImportParams();
            params.setTitleRows(2);
            params.setHeadRows(1);
            params.setNeedSave(true);
            try {
                List<BusOrderPage> list = ExcelImportUtil.importExcel(file.getInputStream(), BusOrderPage.class, params);
                for (BusOrderPage page : list) {
                    BusOrder po = new BusOrder();
                    BeanUtils.copyProperties(page, po);
                    busOrderService.saveMain(po, page.getBusOrderItemList(), page.getBusOrderPicsList());
                }
                return Result.OK("文件导入成功！数据行数:" + list.size());
            } catch (Exception e) {
                log.error(e.getMessage(), e);
                return Result.error("文件导入失败:" + e.getMessage());
            } finally {
                try {
                    file.getInputStream().close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return Result.OK("文件导入失败！");
    }

}
